using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CoreCalc.SheetDefinedFunctions;

namespace CoreCalc.GUI
{
    public partial class AddFunction : Form
    {
        private Workbook wb;
        private SDF sdfwindow;

        public AddFunction(Workbook wb, SDF sdfwindow)
        {
            InitializeComponent();
            this.wb = wb;
            this.sdfwindow = sdfwindow;
            PopulateSheetList();
        }

        private void PopulateSheetList()
        {
            if (wb != null)
            {
                foreach (Sheet sheet in wb)
                {
                    if (sheet.IsFunctionSheet)
                        funcSheetComboBox.Items.Add(sheet);
                }
                if(funcSheetComboBox.Items.Count != 0)
                {
                    funcSheetComboBox.SelectedIndex = 0;
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            errorLabel.Text = "";
            if (nameTextBox.Text == string.Empty)
            {
                errorLabel.Text = "Must enter a valid name";
                return;
            }
            //todo: enforce so that only alfanumeric names are accepted

            if(funcSheetComboBox.SelectedItem == null)
            {
                errorLabel.Text = "Must select a valid function sheet";
                return;
            }

            Sheet sheet = (Sheet)funcSheetComboBox.SelectedItem;
            if (!SdfManager.CreateFunction(nameTextBox.Text, new FullCellAddr("A1", sheet), new FullCellAddr[] {}))
            {
                errorLabel.Text = "That function name is already in use";
                return;
            }
            sdfwindow.ClearInfo();
            sdfwindow.PopulateFunctionListBox(false);
            sdfwindow.PopulateFunctionListBox(nameTextBox.Text);
            Close();
        }
    }
}